<template>
  <!-- 弹窗对话框，根据mode的不同显示不同的标题，支持新增、编辑和查看操作 -->
  <t-drawer
    :visible="dialogVisible"
    :header="mode == 'new' ? '新增' : mode == 'edit' ? '编辑' : mode == 'view' ? '查看' : ''"
    @confirm="handleSubmit"
    :confirmBtn="EDIT_FORM_SAVE_BUTTON(mode)"
    @cancel="handleClose"
    @close="handleClose"
    size="50%"
  >
    <t-form
      ref="formInstance"
      :data="pageData.formData"
      :labelWidth="120"
      :rules="pageData.formRules"
      :disabled="pageData.readOnly"
    >
      <t-form-item label="中文主体名称" name="customerName">
        <t-input
          :showLimitNumber="true"
          maxlength="50"
          v-if="!pageData.readOnly"
          v-model="pageData.formData.customerName"
          placeholder="请输入外国主体名称（中文）"
        />
        <div v-else class="form__text">{{ pageData.formData.customerName }}</div>
      </t-form-item>

      <t-form-item label="英文主体名称" name="englishName">
        <t-input
          :showLimitNumber="true"
          maxlength="50"
          v-if="!pageData.readOnly"
          v-model="pageData.formData.englishName"
          placeholder="请输入外国主体名称（英文）"
        />
        <div v-else class="form__text">{{ pageData.formData.englishName }}</div>
      </t-form-item>

      <t-form-item label="英文简称" name="englishNickname">
        <t-input
          :showLimitNumber="true"
          maxlength="50"
          v-if="!pageData.readOnly"
          v-model="pageData.formData.englishNickname"
        />
        <div v-else class="form__text">{{ pageData.formData.englishNickname }}</div>
      </t-form-item>

      <t-form-item label="国家/地区" name="countryId">
        <InputSelect v-if="!pageData.readOnly" :value="pageData.formData.country" @onClick="handleRegionShow" />
        <div v-else class="form__text">{{ pageData.formData.country }}</div>
      </t-form-item>

      <t-form-item label="备注" name="remark">
        <t-textarea v-if="!pageData.readOnly" v-model="pageData.formData.remark" />
        <div v-else class="form__text">{{ pageData.formData.remark }}</div>
      </t-form-item>
    </t-form>
  </t-drawer>

  <SelectTable
    v-if="pageData.region.show"
    :loading="pageData.region.loading"
    title="选择国家/地区"
    :showDialog="pageData.region.show"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.region.data.records"
    :columns="regionColumns"
    @onConfirm="handleRegionConfirm"
    @onCancel="handleRegionClose"
    :pagination="pageData.region.pagination"
    @page-change="handleRegionPageChange"
    :filter-value="pageData.region.filterValue"
    @filter-change="handleRegionFilterChange"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, ref, toRaw } from "vue";
import { type FormInstanceFunctions } from "tdesign-vue-next";

// TS 类型文件
import type { ISelectTableGroups } from "@/types";

// 工具函数
import { http } from "@/utils/fetch";

// 常量
import { EDIT_FORM_SAVE_BUTTON, PAGINATION_VALUE } from "@/common/constants";

// API
import { getRegionList } from "@/api/region";

// 业务数据
import { tableColumns as regionColumns } from "@/pages/Dashboard/Info/Region/components/columns";

// import { useUserStore } from "@/stores/modules/user";

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    required: true
  }
});

const emits = defineEmits(["close"]);

const formInstance = ref<FormInstanceFunctions | null>(null);

const GET_FORM_PATH = "/funder/findFunderGlobalMainPart"; // 查询接口
const CREATE_FORM_PATH = "/funder/createFunderGlobalMainPart"; // 创建接口
const UPDATE_FORM_PATH = "/funder/updateFunderGlobalMainPart"; // 更新接口

const pageData = reactive({
  readOnly: false,
  formData: {
    id: "",
    createdTime: "",
    createdBy: "",
    status: 0,
    remark: "",
    updatedBy: "",
    updatedTime: "",
    createdByName: "",
    updatedByName: "",
    hasDeleted: 0,
    customerName: "",
    englishName: "",
    englishNickname: "",
    countryId: "",
    country: ""
  },
  formRules: {
    customerName: [{ required: true, message: "请输入外国主体名称（中文）", type: "error" }],
    englishName: [{ required: true, message: "请输入外国主体名称（英文）", type: "error" }],
    englishNickname: [{ required: true, message: "请输入外国主体简称", type: "error" }],
    countryId: [{ required: true, message: "请选择国家/地区", type: "error" }]
  },
  region: {
    show: false,
    loading: false,
    data: {},
    filterValue: {
      countryName: ""
    },
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups
});

/**
 * 初始化表单数据。
 * 根据不同的操作模式（新增、编辑、查看），加载不同的数据。
 * @param id - ID，用于编辑和查看模式下查询信息。
 */
const initFormData = async (id = "") => {
  if (props.mode === "edit" || props.mode === "view") {
    const resultData = await http("GET", `${GET_FORM_PATH}?id=${encodeURIComponent(id)}`);
    pageData.formData = resultData.data;
  }
};

const getRegionData = async () => {
  pageData.region.loading = true;
  const resultData = await getRegionList(
    pageData.region.pagination.current,
    pageData.region.pagination.pageSize,
    pageData.region.filterValue
  );
  if (resultData.code === 200) {
    pageData.region.data = resultData.data;
    pageData.region.pagination.total = resultData.data.total;
    pageData.region.pagination.current = resultData.data.current;
    pageData.region.pagination.pageSize = resultData.data.size;
    pageData.region.loading = false;
  }
};

const handleRegionConfirm = (e: Record<string, any>) => {
  pageData.formData.countryId = e.options.currentRowData.id;
  pageData.formData.country = e.options.currentRowData.countryName;
  handleRegionClose();
};

const handleRegionShow = () => {
  pageData.region.show = true;
  getRegionData();
};
const handleRegionClose = () => {
  pageData.region.show = false;
};

const handleRegionFilterChange = (filters: Record<string, any>) => {
  pageData.region.filterValue = filters;
  pageData.region.pagination = structuredClone(PAGINATION_VALUE);
  getRegionData();
};

const handleRegionPageChange = (pageInfo: Record<string, any>) => {
  // console.log(pageInfo, newDataSource);
  pageData.region.pagination.pageSize = pageInfo.pageSize;
  pageData.region.pagination.current = pageInfo.current;
  getRegionData();
};

/**
 * 提交表单。
 * 根据不同的操作模式（新增、编辑），调用不同的接口保存信息。
 */
const handleSubmit = async () => {
  const validateResult = await formInstance?.value?.validate();

  /* validateResult 在校验没通过的时候返回的是一个 Object，校验通过的时候返回的是
   * 布尔值 true，所以这里写死判断为 true。
   */
  if (validateResult !== true) {
    return;
  }

  let resultData;

  if (props.mode === "view") {
    handleClose();
  }

  const postFormData = structuredClone(toRaw(pageData.formData));

  if (props.mode === "new") {
    // 新增
    resultData = await http("POST", CREATE_FORM_PATH, postFormData);
  } else {
    // 更新
    // postFormData.updatedTime = new Date().toISOString();
    // postFormData.updatedBy = userStore.userData?.id;

    resultData = await http("POST", UPDATE_FORM_PATH, postFormData);
  }

  // 根据接口返回结果，提示操作成功或失败，并关闭对话框
  if (resultData.code === 200) {
    emits("close", "success");
  }
};

const handleClose = () => {
  // 关闭对话框，并返回取消操作标识
  emits("close", "cancel");
};

// 如果是查看模式，设置表单为只读
if (props.mode == "view") {
  pageData.readOnly = true;
}

// 初始化表单数据，根据传入的 ID
initFormData(props.id);
</script>
